#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include "libgrf.h"

int extract(const char* grfFile, const char* src, const char* dest);

// grf [grf file] [target name] [output file]
int main(int argc, char* argv[])
{
#ifdef _DEBUG
	for (int i = 0; i < argc; i++)
	{
		printf("arg[%d]:%s\n", i, argv[i]);
		
	}
#endif //_DEBUG

	int ret = 1;

	if (argc < 4){
		printf("Parameter error.\n");
		printf("Call: grf [grf file] [target name] [output file]\n");
	
	}
	else{
		ret = extract(argv[1], argv[2], argv[3]);
	}

	return ret;
}

int extract(const char* grfFile, const char* src, const char* dest)
{
	grf_handle handle = grf_load(grfFile, false);
	if (handle == NULL){
		printf("Failed! Please check that `%s' is a valid Gravity Ragnarok File.\n", grfFile);
		return 1;
	}
	grf_node node = grf_get_file(handle, src);
	if (node == NULL){
		printf("Error (grf_get_file)\n");
		grf_free(handle);
		return 1;
	}
	
	int size = grf_file_get_size(node);
	void* ptr = malloc(size);
	
	if ((ptr == NULL) || (grf_file_get_contents(node, ptr) != size)) {
		printf("Error (get_contents)\n");
		free(ptr);
		return 1;
	}

	FILE *f;
	
	errno_t e = fopen_s(&f, dest, "wb");
	if (e != 0) {
		printf("Error (fopen)\n");
		free(ptr);
		return 1;
	}
	
	fwrite(ptr, size, 1, f);
	
	fclose(f);
	free(ptr);
	grf_free(handle);

	return 0;
}


